package seotools.positions.top;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PRCY {
    public static void main(String[] args) throws IOException, InterruptedException {
        String url = "http://www.sotmarket.ru/category/akb/brand/Nokia.html";
//        String url = "http%3A%2F%2Fwww.sotmarket.ru%2Fcategory%2Fakb%2Fbrand%2FNokia.html";
        String info = getInfo(url);
        System.out.println(info);
    }

    public static String getInfo(String url) throws IOException, InterruptedException {
        url = URLEncoder.encode(url, "UTF-8");
        String hash = getVFaceHash();
        Document document;
        try {
            document = Jsoup.connect("http://vface.controlstyle.ru/?hash=" + hash + "&url=" + url).
                    timeout(30000).get();
        } catch (IOException e) {
            return "?.?";
        }
        String cost = document.select("div#price").get(0).text();
        Elements infoElems = document.select("p.info");
        String params;
        if (infoElems.size() == 0) {
            params = "NA";
        } else {
            params = infoElems.get(0).text();
        }
        return cost + "." + params;
    }

    public static String getVFaceHash() throws IOException {
        Document document = Jsoup.connect("http://vface.controlstyle.ru").
                timeout(30000).get();
        Pattern p = Pattern.compile("value=\"[a-zA-Z-0-9]+\"");
        String hiddenInput = document.select("form#fm script").toString();
        Matcher matcher = p.matcher(hiddenInput);
        boolean result = matcher.find();
        String hash = "";
        if (result) {
            int start = matcher.start() + 7;
            int end = matcher.end() - 1;
            hash = hiddenInput.substring(start, end);
        }
        return hash;
    }
}
